﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LDSBusiness.EventArgs;
using LDSModel.Item;
using LDSModel;
using LDSCore;
using LDSBusiness;
using System.Threading;
using System.IO.Ports;
using Newtonsoft.Json;
using System.IO;
using LDSModel.Dal;

namespace TestFrom
{
    public partial class Form1 : Form
    {
        Thread threadHeartJump;
        int count = 1;

        bool exitMoniThread;
        StreamReader fileReader;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnSendRecord_Click(object sender, EventArgs e)
        {
            Random random = new Random();

            RecordItem record = new RecordItem();
            record.AlarmCount = (uint)count++;
            record.AlarmTime = DateTime.Now;
            record.Ch1Value = float.Parse((random.Next(-Constant.MaxElectricValue, Constant.MaxElectricValue) / 1000.0).ToString("0.000"));
            record.Ch2Value = float.Parse((random.Next(-Constant.MaxElectricValue, Constant.MaxElectricValue) / 1000.0).ToString("0.000"));

            DataSender.Instance.SendRecord(1012, record);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DeviceService.Instance.Refush();

            //DataRecipient.Instance.OnMsgProcess += new DelegateMsgProcess(Instance_OnMsgProcess);

            SerialPort serialPort = new SerialPort("COM2");
            serialPort.BaudRate = 38400;
            DataRecipient.Instance.Start(serialPort);
        }

        void Instance_OnMsgProcess(object sender, MsgProcessEventArgs args)
        {
            MsgItem msg = args.Msg;

            //if (msg.DestAddr == 1011 || msg.DestAddr == 1013 || msg.DestAddr == 1041)
            switch ((MsgType)msg.MsgType)
            {
                #region 复位系统
                case MsgType.ZGCMD_RESET:
                    {
                        DataSender.Instance.Answer(msg, true);
                    }
                    break;
                #endregion

                #region 恢复默认设置
                case MsgType.ZGCMD_DEFAULT:
                    {
                        DataSender.Instance.Answer(msg, true);
                    }
                    break;
                #endregion

                #region 读取系统信息
                case MsgType.ZGCMD_READ_SYSINFO:
                    {
                        DataSender.Instance.SendSystemInfo((int)msg.DestAddr);
                    }
                    break;
                #endregion

                #region 读取系统时间
                case MsgType.ZGCMD_READ_SYSTIME:
                    {
                        DataSender.Instance.SendSystemTime((int)msg.DestAddr);
                    }
                    break;
                #endregion

                #region 设置系统时间
                case MsgType.ZGCMD_SET_SYSTIME:
                    {
#if _TRACE
                        Console.WriteLine(string.Format("同步时间： 线程Id({0}),发送地址({1})),时间({2})", Thread.CurrentThread.ManagedThreadId, msg.DestAddr, DateTime.Now));
#endif
                        DataSender.Instance.Answer(msg, true);
                    }
                    break;
                #endregion

                #region 查询工作状态
                case MsgType.ZGCMD_CHECK_STATE:
                    {
                        DataSender.Instance.SendHeartjump((int)msg.DestAddr);
                    }
                    break;
                #endregion

                #region 读取报警次数
                case MsgType.ZGCMD_READ_ALARMCOUNT:
                    {
                    }
                    break;
                #endregion

                #region 读取一条雷电流
                case MsgType.ZGCMD_READ_RECORD:
                    {
                        Random random = new Random();
                        RecordItem item = new RecordItem();
                        item.AlarmTime = DateTime.Now;
                        item.AlarmCount = BitConverter.ToUInt16(msg.Buffer, 0);
                        item.Ch1Value = float.Parse((random.Next(-Constant.MaxElectricValue, Constant.MaxElectricValue) / 1000.0).ToString("0.000"));
                        item.Ch2Value = float.Parse((random.Next(-Constant.MaxElectricValue, Constant.MaxElectricValue) / 1000.0).ToString("0.000"));

                        DataSender.Instance.SendRecord(msg.DestAddr, item, MsgType.ZGCMD_ANSWER_OK);
                    }
                    break;
                #endregion

                #region 清空存储记录
                case MsgType.ZGCMD_CLEAR_RECORDS:
                    {
                        DataSender.Instance.Answer(msg, true);
                    }
                    break;
                #endregion
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (threadHeartJump == null)
            {
                threadHeartJump = new Thread(new ThreadStart(new DelegateEmpty(timerHeartjump_Tick)));
                threadHeartJump.IsBackground = true;
                threadHeartJump.Start();
                button1.Text = "关闭心跳包";
            }
            else
            {
                try
                {
                    threadHeartJump.Abort();
                }
                catch
                { }
                threadHeartJump = null;
                button1.Text = "开启心跳包";
            }
        }

        private void timerHeartjump_Tick()
        {
            while (true)
            {
                foreach (Data_Device device in DeviceService.Instance.DeviceList)
                {
                    DataSender.Instance.SendHeartjump(device.Address.Value);
                    Thread.Sleep(100);
                }
                Thread.Sleep(5000);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //byte[] data = new byte[2];
            //int index = 0x12345678;
            //data[0] = Convert.ToByte(index & 0xff);
            //data[1] = Convert.ToByte(index / 256);

            ushort a = 0;

            int b = int.MaxValue;

            a = (ushort)b;
        }

        private void btnMoli_Click(object sender, EventArgs e)
        {
            if (null == btnMoli.Tag)
            {
                ThreadExecutor.Execute(new WaitCallback(moni));

                btnMoli.Text = "模拟中...";

                btnMoli.Tag = 1;
            }
            else
            {
                exitMoniThread = true;

                btnMoli.Text = "设备模拟";

                btnMoli.Tag = null;
            }
        }

        void moni(object state)
        {
            int waitTime = 10000;

            while (true)
            {
                if (exitMoniThread)
                {
                    exitMoniThread = false;
                    return;
                }

                ThreadExecutor.Execute(new WaitCallback(SendRecord));
                
                Thread.Sleep(waitTime);

                sendIndex++;
            }
        }

        void SendRecord(object address)
        {
            foreach (Data_Device device in DeviceService.Instance.DeviceList)
            {
                Random random = new Random();

                RecordItem record = new RecordItem();
                record.AlarmCount = (uint)sendIndex + 5;
                record.AlarmTime = DateTime.Now;
                record.Ch1Value = float.Parse((random.Next(-Constant.MaxElectricValue, Constant.MaxElectricValue) / 1000.0).ToString("0.000"));
                record.Ch2Value = float.Parse((random.Next(-Constant.MaxElectricValue, Constant.MaxElectricValue) / 1000.0).ToString("0.000"));

                DataSender.Instance.SendRecord(device.Address.Value, record);

                sendCount++;

                Invoke(new UpdateMsgDelegate(RefushCount));
#if _TRACE
                Console.WriteLine(string.Format("线程Id：{0},发送地址:{1},发送数据:{2}", Thread.CurrentThread.ManagedThreadId, device.Address, JsonConvert.SerializeObject(record)));
#endif
            }
        }

        static int sendIndex;
        static int sendCount;
        static int sendFileCount;
        delegate void UpdateMsgDelegate();

        void RefushCount()
        {
            label1.Text = string.Format("发送{0}条数据.", sendCount);
        }

        void RefushFileCount()
        {
            label2.Text = string.Format("发送{0}条数据.", sendFileCount);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ThreadExecutor.Execute(new WaitCallback(SendFileRecord));
        }

        void SendFileRecord(object address)
        {
            sendFileCount = 0;

            FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logbyte1.txt"), FileMode.Open);

            StreamReader reader = new StreamReader(file);

            while (!reader.EndOfStream)
            {
                string strData = reader.ReadLine();
                strData = strData.Split('，')[0];
                strData = strData.Split('：')[1];
                strData = strData.Replace("-", "");
#if _TRACE
                Console.WriteLine(string.Format("线程Id：{0},发送数据:{1}", Thread.CurrentThread.ManagedThreadId, strData));
#endif
                DataSender.Instance.SendData(strData);

                sendFileCount++;

                Invoke(new UpdateMsgDelegate(RefushFileCount));

                Thread.Sleep(1000);
            }

            reader.Close();

            file.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (null == fileReader)
            {
                FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logbyte1.txt"), FileMode.Open);

                fileReader = new StreamReader(file);
            }

            if (!fileReader.EndOfStream)
            {
                string strData = fileReader.ReadLine();
                strData = strData.Split('，')[0];
                strData = strData.Split('：')[1];
                strData = strData.Replace("-", "");

                //Console.WriteLine(string.Format("线程Id：{0},发送数据:{1}", Thread.CurrentThread.ManagedThreadId, strData));

                DataSender.Instance.SendData(strData);

                sendFileCount++;

                Invoke(new UpdateMsgDelegate(RefushFileCount));
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = RecordService.Query(
                ("").ToString(),
                ("").ToString(),
                DateTime.Now, DateTime.Now);
        }
    }
}
